<template>
  <view class="padding-lg bg-white" style="min-height:100vh">
    <view class="padding">
      <view class="text-lg">门急诊患者及陪诊人员流行病学史调查表（第十版）</view>
      <view class="margin-top-sm" style="line-height:1.5">
        <text class="text-gray">为认真落实国家、省、市疫情防控要求，切实保障患者安全和做好新冠病毒感染筛查工作，杜绝病毒
        在医院感染传播，根据《中华人民共和国传染病防治法》等相关法律法规要求，请您配合我们填写以下内容，同时我院负责保护您所
        填写的个人信息安全，请放心填写。</text>
        <text class="text-bold" style="text-decoration:underline;">
          请您务必如实填报，如故意隐瞒相关情况，造成后果，将承担相应法律责任。
        </text>
      </view>

      <view class="margin-tb-xl">
        <text class="text-red">如您出现以下情况之一，请您首先到设有发热门诊的医疗机构就医筛查。</text>
      </view>
      
      <evan-form :hide-required-asterisk="true" :label-style="labelStyles" 
        ref="form" :model="formInfo" class="no-bottom-border">

        <view v-for="(ques, i) in questionsList" :key="i" class="margin-bottom-lg">
          <evan-form-item label="" :prop="`ques${i}`" label-position="left">
            <view>
              <view>{{ques.note}}</view>
              <radio-group @change="radioChange(i,$event)" class="margin-top">
                <label class="margin-right" style="display:inline-flex;align-items:center" v-for="(op, index) in ynOpts" :key="index">
                  <radio class="margin-right-xs" :value="op.value" :checked="formInfo[`ques${i}`] == op.value" color="#3182F8" />
                  <view>{{op.label}}</view>
                </label>
              </radio-group>
            </view>
          </evan-form-item>

          <evan-form-item v-if="ques.showOpen" :label="ques.memo" :prop="`text_ques${i}`" label-position="top">
            <view class="i-input">
              <input type="text" v-model="formInfo[`text_ques${i}`]" placeholder="请输入" />
            </view>
          </evan-form-item>
        </view>

        <view class="margin-top-xl">
          <button :disabled="submiting" @click="onSubmit" class="cu-btn lg btn-fluid bg-primary">提交</button>
        </view>
      </evan-form>
    </view>
    <cu-bar></cu-bar>
  </view>
</template>

<script>
import CheckAuthMixin from '@/mixins/CheckAuthMixin'

const CACHE_KEY = 'ts_matters_submiting'

const FormInfo = {
  // ques0: '',
  // ques1: '',
  // ques2: '',
}

export default {
  mixins: [
    CheckAuthMixin,
  ],
  data() {
    return {
      labelStyles: {
        minWidth: '80px',
        textAlign: 'justify',
        paddingRight: '30upx',
        fontSize: '30upx',
        color: 'inherit',
      },
      submiting: false,
      formInfo: Object.assign({}, FormInfo),
      formRules: {
        // ques0: [
        //   { required: true, message: '请选择选项' },
        // ]
      },
      userInfo: {},
      ynOpts: [
        { label: '是', value: '1' },
        { label: '否', value: '2' },
      ],
      questionsList: [],
    }
  },
  watch: {
    submiting(val) {
      if (val) {
        uni.showLoading()
      } else {
        uni.hideLoading()
      }
    },
  },
  onLoad(opts) {
    this.loadState()

    /**
     * TODO:
     */
    this.$http({
      url: '/api/Invest/GetAllEpideinves',
      method: 'POST',
      success: (res) => {
        if (res.success) {
          // {
          //   "epide_id": 1,
          //   "note": "1、您是否来自外地？",
          //   "memo": "具体地区：",
          //   "seq": 1,
          //   "temp_type": "1",
          // negative  =1  选是就过不去   0的选是可以过
          //   "negative": "0"

          //    showOpen: false,
          // },
          
          res.data.forEach((it,i) => {
            it.showOpen = false

            this.formInfo[`ques${i}`] = ''
            if (it.temp_type == '1') {
              this.formInfo[`text_ques${i}`] = ''
            }
            this.formRules[`ques${i}`] = [
              { required: true, message: '请选择选项' },
            ]
            if (it.temp_type == '1') {
              this.formRules[`text_ques${i}`] = [
                {
                  validator: (rule, value, callback) => {
                    if (this.formInfo[`ques${i}`] == '1' && !value) {
                      callback(new Error(`请填写${it.memo}`))
                    } else {
                      callback()
                    }
                  },
                }
              ]
            }
          })

          this.questionsList = res.data

          this.$refs.form.setRules(this.formRules)
        }
      }
    })
  },
  mounted() {
    // this.$refs.form.setRules(this.formRules)
  },
  methods: {
    radioChange(i, e) {
      const val = e.detail.value
      this.$set(this.formInfo, `ques${i}`, val)
      const ques = this.questionsList[i]
      if (ques.temp_type == '1' && val == '1') {
        this.$set(this.questionsList[i], 'showOpen', true)
      } else {
        this.$set(this.questionsList[i], 'showOpen', false)
      }
    },
    loadState() {
      const cached = this.$utils.tempPageData.get(CACHE_KEY)
      if (cached) {
        this.userInfo = cached
        this.$utils.pLog('== user info: ', this.userInfo)
      }
    },
    saveState() {
      this.$utils.tempPageData.set(this.userInfo, CACHE_KEY)
    },
    onSubmit() {
      this.$refs.form.validate((res) => {
        if (res) {
          this.$utils.pLog('== submiting: ', this.formInfo)

          const findDanger = Object.keys(this.formInfo).find(k => {
            if (k.indexOf('ques') == 0) {
              if (this.formInfo[k] == '1') {
                const inx = Number(k.replace('ques',''))
                if (this.questionsList[inx].negative == '1') {
                  return true
                }
              }
            }
            return false
          })
          if (findDanger) {
            uni.showModal({
              title:'请您到设有发热门诊的医疗机构就医筛查！',
              showCancel: false
            })
          } else {
            const { pat_id } = this.userInfo
            
            this.$http({
              url: '/api/Invest/Save',
              method: 'POST',
              data: {
                pat_id,
                epide: this.questionsList.map((x,i) => ({
                  epide_id: x.epide_id,
                  epide_values: this.formInfo[`ques${i}`] == '1' ? '是' : '否',
                  memo: this.formInfo[`text_ques${i}`] || '',
                }))
              },
              success: (res) => {
                if (res.success) {
                  const inves_id = res.data
                  this.userInfo.inves_id = inves_id
                  this.saveState()
                  this.gotoStep3()
                }
              }
            })
          }
        }
      })
    },
    gotoStep3() {
      uni.navigateTo({
        url: `/pages/hesuanyuyue/step3/index`
      })
    },
  },
}
</script>

<style scoped>
.bg-cus-blue {
  background: #3182F8;
}
.no-bottom-border /deep/ .evan-form-item-container {
  border-bottom: none;
}
</style>